﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Wedo.Domain.Models;
using EFCachingProvider.Caching;
using System.Data.Entity;
using EFCachingProvider;
using System.Web.Caching;

namespace Wedo.Recognition.Repository
{ 
    public class RoleRepository :  IRoleRepository
    {
        #region 一般方法
        private const string DependentEntitySetPrefix = "dependent_entity_set_";
        private const string key = "Role";

        private ICache _Cache;
        private readonly DbContext _dbContext;
        private readonly DbSet<Role> _dbSet;
        public RoleRepository(DbContext dbContext)
        {
            _dbContext = dbContext;
            _dbSet = dbContext.Set<Role>();
            _Cache = EFCachingProviderConfiguration.DefaultCache;
        }

        public List<Role> GetRoleByNames(IEnumerable<string> roles)
        {
            return All().Where(m => roles.Any(s => s == m.Id)).ToList();
        }

        public Role GetRole(string role)
        {
            return All().Find(m => m.Id == role);
        }

        public Role Create(Role entity)
        {
            var model = _dbSet.Add(entity);
            _dbContext.SaveChanges();
            return model;
        }

        public void Delete(string id)
        {

            if (_dbContext.Set<UserInfo>().Count(m => m.Roles.Any(s => s.Id == id)) > 0)
            {
                throw new Exception("有此角色的用户，不能删除");
            }
            var model = _dbSet.Find(id);
            if (model != null)
            {
                _dbSet.Remove(model);
                _dbContext.SaveChanges();
            }
        }

        public Role Update(Role entity)
        {
            var model = _dbSet.Find(entity.Id);
            if (model != null)
            {
                _dbContext.Entry(model).CurrentValues.SetValues(entity);
                _dbContext.SaveChanges();
            }
            return model;
        }

        public List<Role> All()
        {
            object data = null;
            if (_Cache.GetItem(key, out data) == false)
            {
                if (data == null)
                {
                    data = _dbSet.ToList();
                    _Cache.PutItem(DependentEntitySetPrefix + key, data,
                        new string[] { key }, Cache.NoSlidingExpiration, Cache.NoAbsoluteExpiration);
                }
            }
            return data as List<Role>;
        } 
        #endregion

    }
}
